Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

426
Visualizações
PHP -> How to sum array values using foreach

I am new developer. I have a problem. I want all rating value sum then divided with 5. foreach show 325. I want result 3+2+5=10 then 10/5=2

 foreach ($ratings as $ratingss)  {                          
     echo $ratingss->rating ;
     }

var dump

object(stdClass)[571]
  public 'id' => string '12' (length=2)
  public 'hotel_id' => string '37' (length=2)
  public 'rating' => string '3' (length=1)

object(stdClass)[300]
  public 'id' => string '13' (length=2)
  public 'hotel_id' => string '37' (length=2)
  public 'rating' => string '5' (length=1)
over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

You can use this code. It will sum all values and put in the $sum variable.

if your array object(stdClass) -> then

$sum = 0; // this is store all sum value so first assign 0
foreach ($ratings as $ratingss)          
{
   $sum += $ratingss->rating; // sum value with previous value and store it and no need to convert string type to int cause php do it 
}
echo $sum; // this is final value
echo $final_result = $sum / 5; // this is your desire result 

if your array -> associative array then

$sum = 0; // this is store all sum value so first assign 0
foreach ($ratings as $ratingss)           
{
   $sum += $ratingss['rating']; // sum value with previous value and store it and no need to convert string type to int cause php do it 
}
echo $sum; // this is final value
echo $final_result = $sum / 5; // this is your desire result 

hope this will help you

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda